import { ForbiddenException, Injectable } from '@nestjs/common'
import { LoginDto } from './dto/login.dto'
import { JwtService } from '@nestjs/jwt'
import { PrismaService } from 'src/prisma/prisma.service'
import { hash, verify } from 'argon2'
import { RegistetDto } from './dto/register.dto'

@Injectable()
export class AutoService {
  constructor(
    private readonly jwt: JwtService,
    private prisma: PrismaService,
  ) {}

  async login({ name, password }: LoginDto) {
    const user = await this.prisma.user.findUnique({
      where: { name },
    })

    if (!(await verify(user.password, password))) throw new ForbiddenException('密码输入错误')
    return {
      token: await this.jwt.signAsync({
        username: user.name,
        sub: user.id,
      }),
      userId: user.id,
    }
  }

  async register(registerDto: RegistetDto) {
    return await this.prisma.user.create({
      data: {
        name: registerDto.name,
        email: registerDto.email,
        password: await hash(registerDto.password),
      },
    })
  }

  async findOne(id: number) {
    return await this.prisma.user.findFirst({ where: { id } })
  }
}
